package com.yyj1205.jsongenrator.service.Implement;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.yyj1205.jsongenrator.Util.RedisUtil;
import com.yyj1205.jsongenrator.config.ErineBotConfig;
import com.yyj1205.jsongenrator.entity.ChatMessage;
import com.yyj1205.jsongenrator.entity.ErintBotParam;
import com.yyj1205.jsongenrator.entity.ErnieBotTurboResponse;
import com.yyj1205.jsongenrator.entity.session.RedisSession;
import com.yyj1205.jsongenrator.service.ErnieBotService;
import com.yyj1205.jsongenrator.service.FileService;
import com.yyj1205.jsongenrator.service.ParseService;
import okhttp3.*;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Title: ErineBotServiceImpl
 * @Author yyj1205
 * @Package com.yyj1205.jsongenrator.service.Implement
 * @Date 2024-09-22 20:03
 * @description:
 */
@Service
public class ErineBotServiceImpl implements ErnieBotService {
    @Resource
    private RedisUtil redisUtil;
    @Autowired
    ErineBotConfig erineBotConfig;
    @Autowired
    ParseService parseService;
    @Autowired
    FileService fileService;
    static final OkHttpClient okHttpClient = new OkHttpClient().newBuilder().build();
    @Override
    public String getSession(String userName) {
        UUID uuid = UUID.randomUUID();
        String uuidStr = uuid.toString();
        if(redisUtil.set(uuidStr, new RedisSession(uuidStr, userName, new ArrayList<>()), 600)){
            return uuidStr;
        }
        else {
            return null;
        }
    }

    @Override
    public void deleteSession(String sessionId) {
        redisUtil.del(sessionId);
    }

    @Override
    public String postMessage(String session_Id, String msg) throws IOException {
        if(msg == null || msg.isEmpty()) {
            throw new RuntimeException("No msg Included.");
        }
        RedisSession redisSession = (RedisSession) redisUtil.get(session_Id);
        if (redisSession == null) throw new RuntimeException("Illegal SessionId");
        List<ChatMessage> messages = redisSession.getMessageList();
        messages.add(new ChatMessage("user", msg));
        ErintBotParam erintBotParam = new ErintBotParam(messages,
                erineBotConfig.getTemperature(),
                erineBotConfig.getTop_p(),
                erineBotConfig.getPenalty_score(),
                erineBotConfig.getSystem(),
                erineBotConfig.isDisable_search(),
                erineBotConfig.getMax_output_token(),
                erineBotConfig.getResponse_format(),
                session_Id);
        String postMsg = HttpUtil.post(erineBotConfig.getInstanceuri() + "?access_token=" +
                        getAccessToken(erineBotConfig.getAppKey(), erineBotConfig.getSecretKey()),
                JSONUtil.toJsonStr(erintBotParam));
        System.out.println(postMsg);
        ErnieBotTurboResponse response = JSONUtil.toBean(postMsg, ErnieBotTurboResponse.class);
        messages.add(new ChatMessage("assistant", response.getResult()));
        redisSession.setMessageList(messages);
        redisUtil.set(session_Id, redisSession, 6000);
        return response.getResult();
    }

    @Override
    public void loadMessage(String session_Id) throws IOException {
        RedisSession redisSession = (RedisSession) redisUtil.get(session_Id);
        if (redisSession == null) throw new RuntimeException("Illegal SessionId");
        List<ChatMessage> messages = redisSession.getMessageList();
        List<com.alibaba.fastjson.JSONObject> jsonList = parseService.extractJsons(messages.get(messages.size() - 1).getContent());
        if(jsonList == null || jsonList.size() == 0) { throw new RuntimeException("No message"); }
        for(com.alibaba.fastjson.JSONObject json: jsonList){
            fileService.saveForms(json.getString("name") , redisSession.getUserName(),parseService.generateFormJson(json));
            fileService.saveTables(json.getString("name") , redisSession.getUserName(),parseService.generateTableJson(json));
            fileService.saveModels(json.getString("name") , redisSession.getUserName(),parseService.generateModelJson(json));
        }
    }

    public String getAccessToken(String apiKey, String secretKey) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + apiKey
                + "&client_secret=" + secretKey);
        Request request = new Request.Builder()
                .url(erineBotConfig.getTokenuri())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = okHttpClient.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }
}
